package com.antis.olsl.magic.order;

import android.text.TextUtils;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.antis.olsl.arouterlib.MagicRoutePath;
import com.antis.olsl.base.BaseActivity;
import com.antis.olsl.library.dialog.ChooseDateDialog;
import com.antis.olsl.library.dialog.ChooseSalesroomDialog;
import com.antis.olsl.library.response.SalesroomOrWarehouseInfo;
import com.antis.olsl.base.utils.ToastUtil;
import com.antis.olsl.library.widget.ChooseSalesroomView;
import com.antis.olsl.magic.databinding.ActivityGuestListBinding;
import com.antis.olsl.magic.response.GetGuestListResp;
import com.trello.rxlifecycle2.LifecycleTransformer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import timber.log.Timber;

/**
 * 三级客单
 *
 * @author hhh
 */
@Route(path = MagicRoutePath.ACTIVITY_GUEST_LIST)
public class GuestListActivity extends BaseActivity<ActivityGuestListBinding> implements ChooseSalesroomView.ChooseSalesroomListener,
        ChooseSalesroomDialog.ChooseSalesroomListener, GuestListContract.View, ChooseDateDialog.ChooseDateListener {

    private boolean chooseAllSalesroom = true;
    private ArrayList<SalesroomOrWarehouseInfo> salesroomInfos = new ArrayList<>();
    private ArrayList<SalesroomOrWarehouseInfo> selectedSalesroomInfos = new ArrayList<>();
    private ChooseSalesroomDialog mDialog;

    private ChooseDateDialog chooseDateDialog;

    private GuestListPresenter mPresenter;

    private Date startDate;
    private Date endDate;
    private int pageNum = 1;
    private String salesRoomIds = "";
    private SimpleDateFormat textDateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());

    @Override
    protected ActivityGuestListBinding getViewBinding() {
        return ActivityGuestListBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }

    @Override
    protected void initPresenter() {
        super.initPresenter();
        mPresenter = new GuestListPresenter();
        mPresenter.takeView(this);
    }

    @Override
    protected void initViews() {
        initDate();

        viewBinding.layoutChooseSalesroom.chooseSalesroomView.setSalesroom();
        viewBinding.layoutChooseSalesroom.chooseSalesroomView.setChooseSalesroomListener(this);
        viewBinding.rlChooseDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseDateDialog = new ChooseDateDialog(GuestListActivity.this, "选择时间", startDate, GuestListActivity.this, "startDate");
            }
        });
    }

    private void initDate() {
        Calendar calendar = Calendar.getInstance();

        endDate = new Date();
        calendar.setTime(endDate);
        //初始进来查询近7天的数据
        calendar.add(Calendar.DATE, -7);
        startDate = calendar.getTime();
        setDateText();
    }

    private void setDateText() {
        String date = textDateFormat.format(startDate) + "-" + textDateFormat.format(endDate);
        viewBinding.tvDate.setText(date);
    }

    @Override
    protected void initData() throws IllegalAccessException {
        loadData();
    }

    private void loadData() {
        Map<String, Object> map = new HashMap<>(3);
        map.put("shopId", salesRoomIds);
        map.put("startTime", dateFormat.format(startDate));
        map.put("endTime", dateFormat.format(endDate));
        mPresenter.getGuestList(map);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mPresenter) {
            mPresenter.unSubscribe();
        }
        if (null != mDialog) {
            mDialog.dismiss();
        }
    }

    @Override
    public void clickChooseListener() {
        if (salesroomInfos == null || salesroomInfos.size() == 0) {
            getSalesroomInfoList();
        } else {
            mDialog = new ChooseSalesroomDialog(this, salesroomInfos, GuestListActivity.this);
        }
    }

    /**
     * 获取门店或仓库列表
     */
    private void getSalesroomInfoList() {
        HashMap<String, Object> map = new HashMap<>();
        mPresenter.getSalesroomInfoList(map);
    }

    @Override
    public void clickPhone(String phone) {

    }

    @Override
    public void onChooseSalesroomListener(boolean isChooseAll, ArrayList<SalesroomOrWarehouseInfo> choosedFiledInfos, ArrayList<SalesroomOrWarehouseInfo> sourceInofs, int selectedIndex) {
        chooseAllSalesroom = isChooseAll;
        salesroomInfos = sourceInofs;
        selectedSalesroomInfos = choosedFiledInfos;
        pageNum = 1;
        if (selectedIndex == -1) {
            salesRoomIds = "";
        } else {
            salesRoomIds = filterIds();
        }
        loadData();
    }

    public String filterIds() {
        ArrayList<SalesroomOrWarehouseInfo> infos = (chooseAllSalesroom ? salesroomInfos : selectedSalesroomInfos);
        String name = "";
        String ids = "";
        for (int i = 0; i < infos.size(); i++) {

            ids += TextUtils.isEmpty(ids) ? infos.get(i).getId() : "," + infos.get(i).getId();
            if (chooseAllSalesroom) {
                continue;
            }
            name += TextUtils.isEmpty(name) ? infos.get(i).getName() : "," + infos.get(i).getName();
        }
        boolean chooseALL = false;
        if (chooseAllSalesroom) {
            name = "全部门店";
            chooseALL = true;
        }
        viewBinding.layoutChooseSalesroom.chooseSalesroomView.setSalesroomInfos(infos);
        return ids;
    }

    @Override
    public void getSalesroomInfoListSuccess(List<SalesroomOrWarehouseInfo> list) {
        salesroomInfos.clear();
        salesroomInfos.addAll(list);
        Timber.tag("hhh").e("getSalesroomInfoListSuccess resp= " + list.size());

        mDialog = new ChooseSalesroomDialog(this, salesroomInfos, GuestListActivity.this);
    }

    @Override
    public void getSalesroomInfoListFailure(String msg) {
        Timber.tag("hhh").e("getSalesroomInfoListFailure msg= " + msg);
        if (TextUtils.isEmpty(msg)) {
            msg = "请求失败,请稍后重试";
        }
        ToastUtil.showToast(this, msg);
    }

    @Override
    public void getGuestListSuccess(GetGuestListResp.ContentBean bean) {
        if (null != bean) {
            setOrderInfo(bean);

            setHighOrderInfo(bean);

            setCommentOrderInfo(bean);

            setLowOrderInfo(bean);
        }
    }

    private void setOrderInfo(GetGuestListResp.ContentBean bean) {
        if (!TextUtils.isEmpty(bean.pingjunkedanjia)) {
            viewBinding.layoutGuestListData.textAverageUnitPrice.setText(bean.pingjunkedanjia);
        } else {
            viewBinding.layoutGuestListData.textAverageUnitPrice.setText("0");
        }

        if (!TextUtils.isEmpty(bean.postype)) {
            viewBinding.layoutGuestListData.textType.setText(bean.postype);
        } else {
            viewBinding.layoutGuestListData.textType.setText("-");
        }

        if (!TextUtils.isEmpty(bean.liandailv)) {
            viewBinding.layoutGuestListData.textJointRate.setText(bean.liandailv);
        } else {
            viewBinding.layoutGuestListData.textJointRate.setText("-");
        }

        if (!TextUtils.isEmpty(bean.posnumber)) {
            viewBinding.layoutGuestListData.textGuestListNumber.setText(bean.posnumber);
        } else {
            viewBinding.layoutGuestListData.textGuestListNumber.setText("-");
        }

        if (!TextUtils.isEmpty(bean.pindanjia)) {
            viewBinding.layoutGuestListData.textUnitPrice.setText(bean.pindanjia);
        } else {
            viewBinding.layoutGuestListData.textUnitPrice.setText("-");
        }
    }

    private void setHighOrderInfo(GetGuestListResp.ContentBean bean) {
        float highProgress = 0f;
        if (!TextUtils.isEmpty(bean.highzb)) {
            try {
                highProgress = Float.parseFloat(bean.highzb);
            } catch (NumberFormatException e) {
                Timber.tag("hhh").e("exception= " + e);
            }
        }
        viewBinding.layoutHighGuestList.circleProgressBarHigh.setProgress(highProgress);
        if (!TextUtils.isEmpty(bean.highnumber)) {
            viewBinding.layoutHighGuestList.textHighNumber.setText(bean.highnumber);
        } else {
            viewBinding.layoutHighGuestList.textHighNumber.setText("0");
        }

        if (!TextUtils.isEmpty(bean.hightbup)) {
            viewBinding.layoutHighGuestList.textHighYoy.setText(bean.hightbup);
        } else {
            viewBinding.layoutHighGuestList.textHighYoy.setText("-");
        }

        if (!TextUtils.isEmpty(bean.highhbup)) {
            viewBinding.layoutHighGuestList.textHighMom.setText(bean.highhbup);
        } else {
            viewBinding.layoutHighGuestList.textHighMom.setText("-");
        }
    }

    private void setCommentOrderInfo(GetGuestListResp.ContentBean bean) {
        float commentProgress = 0f;
        if (!TextUtils.isEmpty(bean.midzb)) {
            try {
                commentProgress = Float.parseFloat(bean.midzb);
            } catch (NumberFormatException e) {
                Timber.tag("hhh").e("exception= " + e);
            }
        }
        viewBinding.layoutCommentGuestList.circleProgressBarComment.setProgress(commentProgress);
        if (!TextUtils.isEmpty(bean.midnumber)) {
            viewBinding.layoutCommentGuestList.textCommentNumber.setText(bean.midnumber);
        } else {
            viewBinding.layoutCommentGuestList.textCommentNumber.setText("0");
        }

        if (!TextUtils.isEmpty(bean.midtbup)) {
            viewBinding.layoutCommentGuestList.textCommentYoy.setText(bean.midtbup);
        } else {
            viewBinding.layoutCommentGuestList.textCommentYoy.setText("-");
        }

        if (!TextUtils.isEmpty(bean.midhbup)) {
            viewBinding.layoutCommentGuestList.textCommentMom.setText(bean.midhbup);
        } else {
            viewBinding.layoutCommentGuestList.textCommentMom.setText("-");
        }
    }

    private void setLowOrderInfo(GetGuestListResp.ContentBean bean) {
        float lowProgress = 0f;
        if (!TextUtils.isEmpty(bean.lowzb)) {
            try {
                lowProgress = Float.parseFloat(bean.lowzb);
            } catch (NumberFormatException e) {
                Timber.tag("hhh").e("exception= " + e);
            }
        }
        viewBinding.layoutLowGuestList.circleProgressBarLow.setProgress(lowProgress);
        if (!TextUtils.isEmpty(bean.lownumber)) {
            viewBinding.layoutLowGuestList.textLowNumber.setText(bean.lownumber);
        } else {
            viewBinding.layoutLowGuestList.textLowNumber.setText("0");
        }

        if (!TextUtils.isEmpty(bean.lowtbup)) {
            viewBinding.layoutLowGuestList.textLowYoy.setText(bean.lowtbup);
        } else {
            viewBinding.layoutLowGuestList.textLowYoy.setText("-");
        }

        if (!TextUtils.isEmpty(bean.lowhbup)) {
            viewBinding.layoutLowGuestList.textLowMom.setText(bean.lowhbup);
        } else {
            viewBinding.layoutLowGuestList.textLowMom.setText("-");
        }
    }

    @Override
    public void getGuestListFailure(String msg) {
        Timber.tag("hhh").e("getGuestListFailure msg= " + msg);
        if (TextUtils.isEmpty(msg)) {
            msg = "请求失败,请稍后重试";
        }
        ToastUtil.showToast(this, msg);
        setDefaultValue();
    }

    @Override
    public void getGuestListEmpty() {
        Timber.tag("hhh").e("getGuestListEmpty");
        setDefaultValue();
    }

    private void setDefaultValue() {
        viewBinding.layoutGuestListData.textAverageUnitPrice.setText("0");
        viewBinding.layoutGuestListData.textType.setText("-");
        viewBinding.layoutGuestListData.textJointRate.setText("-");
        viewBinding.layoutGuestListData.textGuestListNumber.setText("-");
        viewBinding.layoutGuestListData.textUnitPrice.setText("-");

        viewBinding.layoutHighGuestList.circleProgressBarHigh.setProgress(0);
        viewBinding.layoutHighGuestList.textHighNumber.setText("0");
        viewBinding.layoutHighGuestList.textHighYoy.setText("-");
        viewBinding.layoutHighGuestList.textHighMom.setText("-");

        viewBinding.layoutCommentGuestList.circleProgressBarComment.setProgress(0);
        viewBinding.layoutCommentGuestList.textCommentNumber.setText("0");
        viewBinding.layoutCommentGuestList.textCommentYoy.setText("-");
        viewBinding.layoutCommentGuestList.textCommentMom.setText("-");

        viewBinding.layoutLowGuestList.circleProgressBarLow.setProgress(0);
        viewBinding.layoutLowGuestList.textLowNumber.setText("0");
        viewBinding.layoutLowGuestList.textLowYoy.setText("-");
        viewBinding.layoutLowGuestList.textLowMom.setText("-");
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.bindToLifecycle();
    }

    @Override
    public void getDateListener(String tag, int year, int quarter, int month, int week, int day) {
        Date tmpDate = new Date();
        try {
            tmpDate = simpleDateFormat.parse(year + "-" + month + "-" + day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (tmpDate.getTime() - System.currentTimeMillis() > 0) {
            ToastUtil.showToast(this, "选择时间不能超过当前时间");
            return;
        }
        if ("startDate".equals(tag)) {
            startDate = tmpDate;
            chooseDateDialog.dismiss();
            chooseDateDialog = new ChooseDateDialog(this, "选择结束时间", endDate, this, "endDate");
        } else {
            if (tmpDate.getTime() - startDate.getTime() < 0) {
                ToastUtil.showToast(this, "结束时间必须大于开始时间");
                return;
            }
            endDate = tmpDate;
            chooseDateDialog.dismiss();
            pageNum = 1;
            loadData();
        }
        setDateText();
    }
}
